<?php
/**
 * User_model 
 * 用户模型
 * 
 * @uses TXT_Model
 * @package 
 * @copyright 2003-2011 The PHP Developer
 * @author Smiling Dolphin <dolphin@php5x.com> 
 * @license PHP Version 5.2 {@link http://www.php.net/}
 * @version $id$
 */

class User_model extends TXT_Model {

    /**
     * 状态：普通
     */
    const STATUS_NORMAL = 1;

    /**
     * 状态：删除
     */
    const STATUS_REMOVE = 9;

    /**
     * 用户类型：代理
     */
    const TYPE_AGENT = 1;

    /**
     * 用户类型：普通
     */
    const TYPE_NORMAL = 2;

    /**
     * _table 
     * 表名
     * 
     * @var string
     * @access private
     */
    private $_table = 'users';

    /**
     * __construct
     * 构造函数
     *
     * @access protected
     * @return void
     */
    function __construct() {

        parent::__construct();
        $this->load->database('default');
    }

    /**
     * addUser 
     * 添加用户
     * 
     * @access public
     * @return void
     */
    function addUser() {

        // 如果不是POST，返回false
        if (!$this->input->is_post()) {
            return false;
        }

        // 接收表单数据
        $name = $this->input->post('u_name');
        $passwd = $this->_makePasswd('test');

        $insertData = array(
            'u_name' => 'lahm',
            'u_type' => self::TYPE_AGENT,
            'u_passwd' => $passwd['passwd'],
            'u_salt' => $passwd['salt'],
            'u_p_uid' => 0,
            'u_status' => self::STATUS_NORMAL,
            'u_created' => date($this->config->item('log_date_format'))
        );

        if ($this->_userIsExistsByName($insertData['u_name'])) {
            show_error('user is exists', 500);
        }

        return $this->db->insert($this->_table, $insertData);
    }

    function editUser($uid) {

        // 如果不是POST，返回false
        if (!$this->input->is_post()) {
            return false;
        }

        // 判断uid参数
        if (!$uid) {
            return false;
        }

        // 获取用户数据
        $userInfo = $this->getUserByUid($uid);

        if (!$userInfo) {
            return $this->_return('找不到该用户，您是否超时登录了？', false);
        }

        // 接收表单数据
        $companyName = $this->input->post('uCompanyName');
        $oldPasswd = $this->input->post('opwd');
        $newPasswd = $this->input->post('npwd');
        $reNewPasswd = $this->input->post('renpwd');

        // 更新的用户数据
        $updateData = array();

        if ($oldPasswd || $newPasswd || $reNewPasswd) {
            $opwd = $this->_makePasswd($oldPasswd, $userInfo['u_salt']);

            if ($opwd['passwd'] != $userInfo['u_passwd']) {
                return $this->_return('抱歉，您的旧密码不正确。', false);
            }

            if ($newPasswd != $reNewPasswd) {
                return $this->_return('您两次输入的新密码不匹配', false);
            }

            $passwd = $this->_makePasswd($newPasswd, $userInfo['u_salt']);

            $updateData['u_passwd'] = $passwd['passwd'];
        }

        if ($companyName) {
            $updateData['u_company_name'] = $companyName;
        }

        if ($updateData) {
            $updateData['u_updated'] = date($this->config->item('log_date_format'));
            $ret = $this->db->update($this->_table, $updateData, array('uid' => $uid));

            if ($ret) {
                return $this->_return('修改成功', true);
            } else {
                return $this->_return('服务器繁忙', false);
            }
        } else {
            return $this->_return('没有更新任何内容', false);
        }
    }

    /**
     * getUserByUid 
     * 根据uid获取用户信息
     * 
     * @param integer $uid 用户ID
     * @access public
     * @return array
     */
    function getUserByUid($uid) {

        if (!$uid) {
            return false;
        }

        $query = $this->db->get_where($this->_table, array('uid' => $uid, 'u_status !=' => self::STATUS_REMOVE));
        $data = $query->row_array();

        return $data;
    }

    /**
     * getUserByName 
     * 根据name获取用户信息
     * 
     * @param string $name 用户名
     * @access public
     * @return array
     */
    function getUserByName($name) {

        $query = $this->db->get_where($this->_table, array('u_name' => $name, 'u_status !=' => self::STATUS_REMOVE));
        $data = $query->row_array();

        return $data;
    }

    /**
     * authUser 
     * 校验用户名密码是否正确
     * 
     * @param string $name 用户名
     * @param string $passwd 密码
     * @access public
     * @return boolean
     */
    function authUser($name, $passwd) {

        $userInfo = $this->getUserByName($name);

        if (!$userInfo) {
            return false;
        }

        $vPasswd = $this->_makePasswd($passwd, $userInfo['u_salt']);

        if ($userInfo['u_passwd'] == $vPasswd['passwd']) {
            return $userInfo['uid'];
        } else {
            return false;
        }
    }

    /**
     * delete 
     * 删除用户
     * 
     * @param integer $uid 用户ID
     * @access public
     * @return boolean
     */
    function delete($uid) {

        $deleteData = array(
            'u_status' => self::STATUS_REMOVE,
            'u_deleted' => date($this->config->item('log_date_format'))
        );

        return $this->db->update($this->_table, $deleteData, array('uid' => $uid));
    }

    /**
     * _userIsExistsByName 
     * 根据用户名查询用户是否存在
     * 
     * @param string $name 
     * @access private
     * @return boolean
     */
    private function _userIsExistsByName($name) {

        $query = $this->db->get_where($this->_table, array('u_name' => $name));

        if ($query->num_rows() > 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * _makePasswd 
     * 生成带salt的密码
     * 
     * @param string $passwd 密码原文
     * @param string $salt 混合密码字串
     * @access private
     * @return array
     *  + salt
     *  + passwd
     */
    private function _makePasswd($passwd, $salt = '') {

        if (!$salt) {
            $str = 'abcdefghijklmnopqrstuvwxyz0123456789';
            $count = 9;

            while (-- $count) {
                $salt .= $str{mt_rand(0, 35)};
            }
        }

        $data = array(
            'salt' => $salt,
            'passwd' => md5($passwd . $salt),
            );

        return $data;
    }
}
